var DISCLOURE_PATH_PREFIX = "";
var REPORT_PATH_PREFIX = "";
var REPROT_INFO_PATH = "";
var INSTITUTION_PATH = "";

function setPathPrefix(path){
	DISCLOURE_PATH_PREFIX =  path;
}

function setReportPathPrefix(path){
	REPORT_PATH_PREFIX =  path;
}

function setReportInfoPathPrefix(path){
	REPROT_INFO_PATH =  path;
}

function setInstitutionPathPrefix(path){
	INSTITUTION_PATH =  path;
}

$(function() {
	$('[type=checkbox]').iCheck({
		checkboxClass : 'icheckbox_square-green',
	});
	
	//把访问路径传到js
	setPathPrefix(disclosurePath);
	setReportPathPrefix(reportPath);
	setReportInfoPathPrefix(reprotInfoPath);
	setInstitutionPathPrefix(institutionPath);
	$('#reportFrequency').select2({
		placeholder : "报告频率"
	});
	WASP_WIDGET.triggerDateRangeStyle("q-reportTime-range");
	initPieColor();
	initData();
//	bindFrequencyClick();
//	bindChartInvestClick();
	bindInvestorTimeSelectorClick();
	bindSuperviseTimeSelectorClick();
});

function initData(){
	drawAllPie("1");
	drwChartInvestData("1");
}
//投资者报告单选按钮事件
function bindInvestorTimeSelectorClick(){
	$("div[id='investorTimeSelector']").find("span.subSelector").each(function(index){
		if($(this).attr('reportFrequency') == '1'){
			$(this).toggleClass("font-color-white");
		}
		
		$(this).on('click',function(){
			$('#investorTimeSelector .font-color-white').each(function(index,element){
				$(element).removeClass('font-color-white');
			});
			$(this).toggleClass("font-color-white");
			var reportFrequency = $(this).attr("reportFrequency");
			drwChartInvestData(reportFrequency);
		});
	});
}
//监管报告单选按钮事件
function bindSuperviseTimeSelectorClick(){
	$("div[id='superviseTimeSelector']").find("span.subSelector").each(function(index){
		if($(this).attr('reportFrequency') == '1'){
			$(this).toggleClass("font-color-white");
		}
		$(this).on('click',function(){
			$('#superviseTimeSelector .font-color-white').each(function(index,element){
				$(element).removeClass('font-color-white');
			});
			$(this).toggleClass("font-color-white");
			var reportFrequency = $(this).attr("reportFrequency");
			clearPie();
			drawAllPie(reportFrequency);
		});
	});
}
function bindChartInvestClick(){
	$('#investReportDiv').find('input[type=checkbox]').each(function(index,obj){
		$(obj).on('ifChecked', function(event){
			var reportFrequency = "";
			$('#investReportDiv').find('input[type=checkbox]:checked').each(function(){
				reportFrequency += $(this).val() + ",";
			});
			drwChartInvestData(reportFrequency);
		}).on('ifUnchecked', function(event){
			var reportFrequency = "";
			$('#investReportDiv').find('input[type=checkbox]:checked').each(function(){
				if($(this).val() != null || $(this).val() != ''){
					reportFrequency += $(this).val() + ",";
				}
			});
			drwChartInvestData(reportFrequency);
		});
	});
}

function drwChartInvestData(reportFrequency){
	if(reportFrequency == '' || reportFrequency == null){
		reportFrequency = '1';
	}
	var dateRange = getDateRange(reportFrequency);
	var sp = {};
	sp["sp[reprotDateBgn]"] = dateRange["startDate"].replace(/\//g,"-");
	sp["sp[reprotDateEnd]"] = dateRange["endDate"].replace(/\//g,"-");;
	
	$.ajax({
		type:"GET",
		url:DISCLOURE_PATH_PREFIX+"/countReportData.do?r="+Math.random(),
		data:sp,
		dataType:"json",
		success:function(data){
			var barChart = echarts.init(document.getElementById('investBarChart')); 
			barChart.clear();
			if(data && data.length > 0){
				//类型
				var reportName = new Array();
				//已完成
				var completed = new Array();
				//未完成
				var unCompleted = new Array();
				
				//拼装数据
				for(var i = 0;i<data.length;i++){
					reportName.push(data[i].REPORT_NAME);
					completed.push(data[i].FINISH_FILE_COUNT);
					unCompleted.push(data[i].UNFINISH_FILE_COUNT);
				}
				//$("#investBarChart").html("");
				$("#investBarChart1").hide();
				$("#investBarChart").show();
				drwChartInvest(reportName,completed,unCompleted,reportFrequency);
			}else{
				$("#investBarChart1").html(noDataBoxStr);
				$("#investBarChart1").show();
				$("#investBarChart").hide();
			}
		}
	});
}

function drwChartInvest(reportName,completed,unCompleted,reportFrequency){
	// 条形图表
	var barChart = echarts.init(document.getElementById('investBarChart')); 
	barChart.clear();  
	barChart.showLoading({text: '正在努力的读取数据中...'}); 
	
	var map = {};
	for(var i in reportName){
		if(undefined != completed[i] && undefined != unCompleted[i]){
			map[reportName[i]] = completed[i] + unCompleted[i];
		}
	}
	
	var option = {
		title : {
            text: '',
            x:'30'
        },
	    tooltip : {
	        trigger: 'axis',
	        axisPointer : {            // 坐标轴指示器，坐标轴触发有效
	            type : 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
	        },
	        formatter: function(params, ticket, callback) {
	        	var finishParam = "";//已完成
	        	var unFinishParam = "";//未完成
	        	var title = "";//标题
	        	
	        	for(var i=0;i<params.length;i++){
	        		if(undefined != params[i] && params[i].seriesName == "已完成"){
	        			finishParam = params[i];
	        			title = params[i].name;
	        		}
	        		
	        		if(undefined != params[i] && params[i].seriesName == "未完成"){
	        			unFinishParam = params[i];
	        			title = params[i].name;
	        		}
	        	}
	        	var finishValue = 0;
	        	var unFinishValue = 0;
	        	if(undefined != finishParam && finishParam != ''){
	        		finishValue = finishParam.value;
	        	}
	        	if(undefined != unFinishParam && unFinishParam != ''){
	        		unFinishValue = unFinishParam.value;
	        	}
	        	var finishPercent = "";
	        	var unFinishPercent = "";
	        	
	        	if(map[title] != 0){
	        		if(finishValue == 0 && unFinishValue != 0){
	        			finishPercent = "（0%）";
	        			unFinishPercent = "（100%）";
	        		}else if(unFinishValue == 0 && finishValue != 0){
	        			finishPercent = "（100%）";
	        			unFinishPercent = "（0%）";
	        		}else if(finishValue == 0 && unFinishValue == 0){
	        			finishPercent = "";
	        			unFinishPercent = "";
	        		}else if(finishValue != 0 && unFinishValue != 0){
	        			finishPercent += "（"+ Math.round(finishValue/map[title]*1000)/10 + "%）";
	        			unFinishPercent += "（"+ Math.round(unFinishValue/map[title]*1000)/10 + "%）";
	        		}
	        	}
	        	
	        	return title + "<br />" + 
	        	"已完成：" + finishValue + "个"+finishPercent+"<br />" + 
	        	"未完成：" + unFinishValue + "个" + unFinishPercent;
	        }
	    },
	    legend: {
	    	orient: 'horizontal',
	        data: ['未完成', '已完成']
	    },
	    grid: {
	        containLabel: true
	    },
	    yAxis:  {
	        type: 'category',
	        data: reportName
	    },
	    xAxis: {
	    	name:'数量(个)',
	        type: 'value',
	        minInterval: 1
	    },
	    series: [
	        {
	            name: '已完成',
	            type: 'bar',
	            stack: '总量',
	            label: {
	                normal: {
	                    show: true,
	                    position: 'inside',
	                    color : 'black',
	                    formatter: function(param){
	                    	if(param.data > 0){
	                    		return param.data;
	                    	}
	                    	return '';
	                    }
	                }
	            },
	            data: completed,
	            itemStyle:{
		        	normal:{
		        		color:function(params){
		        			return '#fccf50';
		        		}
		        	}
		        }
	        },
	        {
	            name: '未完成',
	            type: 'bar',
	            stack: '总量',
	            barCategoryGap : '30%',
	            label: {
	                normal: {
	                    show: true,
	                    position: 'inside',
	                    color : 'black',
	                    formatter: function(param){
	                    	if(param.data > 0){
	                    		return param.data;
	                    	}
	                    	return '';
	                    }
	                }
	            },
	            data: unCompleted,
	            itemStyle:{
		        	normal:{
		        		color:function(params){
		        			return '#d8d4d4';
		        		}
		        	}
		        }
	        }
	    ]
	};


	//载入图表  
	loadDrugs(barChart,option); 
	barChart.setOption(option);
	barChart.off("click");
	barChart.on("click", function(param){
		pieConsole(param);
	});
}

function getDateRange(param){
	var dateRange = {};
	var dateUtils = new DateUtils();
	var startDate = null;
	var endDate = null;
	//根据选项指定时间段
	switch (Number(param)) {
	case 1:
		//当日
		startDate = dateUtils.getCurrentDate();
		endDate = dateUtils.getCurrentDate();
		break;
	case 2:
		//本周
		startDate = dateUtils.getWeekStartDate();
		endDate = dateUtils.getWeekEndDate();
		break;
	case 3:
		//本月
		startDate = dateUtils.getMonthStartDate();
		endDate = dateUtils.getMonthEndDate();
		break;
	case 4:
		//近三个月
		startDate = dateUtils.getCurrentDate();
		endDate = dateUtils.getThreeMonthsStartDate();
		break;
	case 5:
		//近半年
		startDate = dateUtils.getCurrentDate();
		endDate = dateUtils.getHalfYearStartDate();
		break;
	case 6:
		//近一年.
		startDate = dateUtils.getCurrentDate();
		endDate = dateUtils.getOneYearStartDate();
		break;
	default:
		//当日
		startDate = dateUtils.getCurrentDate();
		endDate = dateUtils.getCurrentDate();
		break;
	}
	dateRange["startDate"] = startDate;
	dateRange["endDate"] = endDate;
	return dateRange;
}

function pieConsole(param) {
	var reportType = "";
	if(param.name == "发行公告"){
		reportType = "1";
	}
	if(param.name == "到期公告"){
		reportType = "2";
	}
	if(param.name == "重大事项公告"){
		reportType = "3";
	}
	if(param.name == "临时公告"){
		reportType = "4";
	}
	if(param.name == "季报"){
		reportType = "5";
	}
	if(param.name == "半年报"){
		reportType = "6";
	}
	if(param.name == "年报"){
		reportType = "7";
	}
	
	var reportFrequency = $("div[id='investorTimeSelector']").find("span.font-color-white").attr("reportFrequency");
	var fileUpload = "";
	if(param.seriesName == "未完成"){
		fileUpload = "NE";
	}
	if(param.seriesName == "已完成"){
		fileUpload = "E";
	}
	
	var dateRange = getDateRange(reportFrequency);
	var url = encodeURI("/solution/business/investReport/investReportListView.do?sp[reportType]="+reportType+
			"&sp[fileUpload]="+fileUpload+"&sp[reportTimeBeg]=" + dateRange["startDate"] + "&sp[reportTimeEnd]=" + dateRange["endDate"]);
	window.location.href= url;
}

var allContainer = [];

function clearPie(){
	for(var i = 0;i<allContainer.length;i++){
		var pieChart = echarts.init(document.getElementById(allContainer[i])); 
		pieChart.clear(); 
	}
	$("#charContainerCenter").html("");
	allContainer = [];
}

var colorListFinished = ["#64CAF5","#FF8DA9","#BA8FEB","#FFD755",
	'#FFA34A','#B98FEC','#A3D62C','#673A79','#00ACC1',
    '#ED6F70','#2E8BCA','#cd5c5c','#ffa500','#40e0d0',
    '#1e90ff','#ff6347','#7b68ee','#00fa9a','#ffd700',
    '#6699FF','#ff6666','#3cb371','#b8860b','#30e0e0'];

var colorListUnFinished = ["#ECF9FF","#FFF3F7","#F7F4FD","#ff7f50",
	'#BA8FEB','#87cefa','#da70d6','#32cd32','#6495ed',
    '#ff69b4','#ba55d3','#cd5c5c','#ffa500','#40e0d0',
    '#1e90ff','#ff6347','#7b68ee','#00fa9a','#ffd700',
    '#6699FF','#ff6666','#3cb371','#b8860b','#30e0e0'];

var colorMap = {};
var colorData = {};

function initPieColor(){
	var reportInfoList = getReportInfo();
	var institutionList = getInstitutionInfo();
	if(reportInfoList&&reportInfoList.length>0){
		for(var i = 0;i<institutionList.length;i++){
			//colorMap[institutionList[i].instId] = [colorListUnFinished[i],colorListFinished[i]];
			colorMap[institutionList[i].instId] = ["#DADADA",colorListFinished[i]];
		}
	}
	if(reportInfoList&&reportInfoList.length>0){
		for(var i = 0;i<reportInfoList.length;i++){
			var colorArr = colorMap[reportInfoList[i].instId];
			colorData[reportInfoList[i].reportId] = colorArr;
		}
	}
}

function getReportInfo(){
	var reportInfoList;
	$.ajax({
		dataType:"json",
		type:"GET",
		url:REPROT_INFO_PATH+"/getReportInfoList.do?reportType=SUPERVISE_REPORT",
		async:false,
		success:function(data){
			reportInfoList = data;
		},
	});
	return reportInfoList;
}

function getInstitutionInfo(){
	var institutionList;
	$.ajax({
		dataType:"json",
		type:"GET",
		url:REPORT_PATH_PREFIX+"/getReportInstList.do",
		async:false,
		success:function(data){
			institutionList = data;
		},
	});
	return institutionList;
}

function drawAllPie(reportFrequency){
	var dateRange = getDateRange(reportFrequency);
	var sp = {};
	sp["sp[reprotDateBgn]"] = dateRange["startDate"].replace(/\//g,"-");
	sp["sp[reprotDateEnd]"] = dateRange["endDate"].replace(/\//g,"-");
	$.ajax({
		type:"GET",
		url:DISCLOURE_PATH_PREFIX+"/getReportChart.do?r="+Math.random(),
		data:sp,
		dataType:"json",
		success:function(data){
			drawChart(data);
		}
	});
}

var noDataBoxStr = "<div class='data-box'>"+
						"<img src='"+contextPath+"/resources/modules/bootstrap/image/nodata.jpg'>"+
						"<div class='no-data'>当前无数据</div>"+
					"</div>";

function drawChart(data){
	var pieTotalData = [];
	if(data&&data.length>0){
		for(var i = 0;i<data.length;i++){
			var pieDataList = [];
			var reportType = data[i].REPORT_TYPE;
			var pieData1 = {},pieData2 = {},subTitle = {};
			pieData1["name"] = "未完成";
			pieData1["value"] = data[i].UNFINISHCOUNT;
			pieData2["name"] = "已完成";
			pieData2["value"] = data[i].FINISHCOUNT;
			pieDataList.push(pieData1);
			pieDataList.push(pieData2);
			var unionPieData = {};
			unionPieData["pieLTitle"] = data[i].REPORT_NAME+"["+data[i].INST_SNAME+"]";
			unionPieData["pieSTitle"] = data[i].REPORT_NAME;
			unionPieData["reportType"] = data[i].REPORT_TYPE;
			unionPieData["instId"] = data[i].INST_ID;
			unionPieData["data"] = pieDataList;
			unionPieData["colorList"] = colorData[reportType];
			pieTotalData.push(unionPieData);
		}
	}
	if(pieTotalData&&pieTotalData.length>0){
		for (var i = 0; i < pieTotalData.length; i++) {
			allContainer.push("pieChart"+(i+1));
			drawUnionpPieChart("pieChart"+(i+1),pieTotalData[i]);
		}
	}else{
		$("#charContainerCenter").append(noDataBoxStr);
	}
}

function drawUnionpPieChart(chartId,data){
	$("#charContainerCenter").append("<div id='"+chartId+"'  class='subContainer'></div>");
	$("#"+chartId).css("height","45%");
	var pieChart = echarts.init(document.getElementById(chartId)); 
	pieChart.clear();  
	pieChart.showLoading({text: '正在努力的读取数据中...'});
	var option = {
			color: data.colorList,/*["#DADADA",color],*/
			title : {
	            text: data.pieLTitle,
	            x:'center'
	        },
	        tooltip : {
		        trigger: 'item',
		        formatter: "{a} <br/>{b}: {c} ({d}%)"
		        /*formatter: function(params, ticket, callback) {
		        	return data.pieSTitle + "<br />" + 
		        	params.data.name + "：" + params.data.value + "("+ params.percent +"%)"; 
		        }*/
		    },
	        legend: {
	            type: 'scroll',
	            orient: 'vertical',
	            right: '5',
	            bottom: '20',
	            data: ["已完成","未完成"],
	        },
		    series: [
		    	{
		            name:'访问来源',
		            type:'pie',
		            radius: ['35%', '55%'],
		            center:['45%','50%'],
		            /*label: {
		                normal: {
		                    show: true,
		                    position: 'center',
		                    color : 'black',
		                    formatter: function(param){
		                    	if(param.data.name =="已完成"){
		                    		return "已完成:"+param.data.value;
		                    	}
		                    	return '';
		                    }
		                }
		            },*/
		            labelLine: {
		                normal: {
		                    show: true
		                }
		            },
		            itemStyle:{
				    	  normal:{
				    		  label:{
				    			  show: true,
				    			  formatter: '{b} : {c} '
				    		  		},
				    		  labelLine :{show:true}
				    	  	}
				    },
		            /*itemStyle:{
			        	normal:{
			        		color:function(params){
			        			return '#fccf50';
			        			console.log(data.colorList[0]);
			        			if(params.data.name =="已完成"){
		                    		return data.colorList[1];
		                    	}
			        			return data.colorList[0];
			        		}
			        	}
			        },*/
		            data:data.data
		        }
		   ]
		};
	//载入图表  
	loadDrugs(pieChart,option); 
	//防止累计触发
	pieChart.off("click");
	pieChart.on("click", function(param){
		loadRegulatoryReport(param,data.instId,data.reportType,data.pieSTitle);
	});
}

function loadRegulatoryReport (param,instId,reportType,reportTypeName) {
	var reportFrequency = $("div[id='superviseTimeSelector']").find("span.font-color-white").attr("reportFrequency");
	var finishFlag = "";
	if(param.name.indexOf("未完成")>=0){
		finishFlag = "0";
	}
	if(param.name.indexOf("已完成")>=0){
		finishFlag = "1";
	}
	var dateRange = getDateRange(reportFrequency);
	var url = encodeURI("/solution/business/regulatoryReport/regulatoryReportListNew.do?sp[instId]="+instId+"&sp[reportType]="+reportType+"&sp[reportTypeName]="+reportTypeName+
			"&sp[finishFlag]="+finishFlag+"&sp[reportTimeBeg]=" + dateRange["startDate"] + "&sp[reportTimeEnd]=" + dateRange["endDate"]);
	window.location.href= url;
}

function down(){
	var reportFrequency = $("div[id='superviseTimeSelector']").find("span.font-color-white").attr("reportFrequency");
	var dateRange = getDateRange(reportFrequency);
	var actionUrl = encodeURI(REPORT_PATH_PREFIX+"/regulatoryReportDownView.do?sp[reportTimeBeg]=" + dateRange["startDate"] + "&sp[reportTimeEnd]=" + dateRange["endDate"]);
	openDialogNew(actionUrl);
}

function investDown(){
	var reportFrequency = $("div[id='investorTimeSelector']").find("span.font-color-white").attr("reportFrequency");
	var dateRange = getDateRange(reportFrequency);
	var actionUrl = encodeURI(DISCLOURE_PATH_PREFIX+"/investReportDown.do?sp[reportTimeBeg]=" + dateRange["startDate"] + "&sp[reportTimeEnd]=" + dateRange["endDate"]);
	openDialogNew(actionUrl);
}

//加载
function loadDrugs(element,option) {  
	element.setOption(option, true);  
	element.hideLoading();
	window.onresize = function () {
		element.resize();
    }
} 